package TextGeneration;

import java.util.ArrayList;

import rules.Rules;

import components.Component;
import features.Feature;

public class Unification {

	public static ArrayList<Component> unify(Component rule, Component semRep) {
		ArrayList<Component> newResults = new ArrayList<>();
		if (!(rule.getName().equalsIgnoreCase(semRep.getName()))) {
			return null;
		} else {
			ArrayList<Feature> ruleFeatureList = rule.getFeatures();
			for (Feature feature : ruleFeatureList) {
				Boolean match = false;
				ArrayList<Feature> semFeatureList = semRep.getFeatures();
				for (Feature feat : semFeatureList) {
					if (feature.getName().equalsIgnoreCase(feat.getName())
							&& feature.getValue().equalsIgnoreCase(
									feat.getValue()))
						match = true;
				}
				if (!match) // match == false
					return null;
			}
			ArrayList<Component> ruleChildren = new ArrayList<>();
			System.out.println(rule.getChildren().getChildren().size() + "SIIIZE");
			if (rule.getChildren() != null) {
				ruleChildren = rule.getChildren().getChildren();
			}
			for (Component r : ruleChildren) {
				Boolean match = false;
				ArrayList<Component> semChildren = semRep.getChildren()
						.getChildren();
				for (Component s : semChildren) {
					ArrayList<Component> thisResult = new ArrayList<>();
					thisResult = unify(r, s);
					if (thisResult != null) {
						for (Component tr : thisResult) {
							newResults.add(tr);
						}
						match = true;
					}

				}
				if (!match) {
					return null;
				}
			}

		}

		return newResults;
	}

}
